﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Helpers;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;

namespace Eneta.Portal.NewsAndBlogs.Controls
{
    public class NewsListControl : UserControl
    {
        protected Repeater postsRepeater;

        protected HtmlGenericControl pager;
        protected HtmlGenericControl pagerPrevContainer;
        protected HtmlGenericControl pagerNextContainer;
        protected HtmlAnchor pagerPrevLink;
        protected HtmlAnchor pagerNextLink;

        protected HtmlGenericControl pagerBottom;
        protected HtmlGenericControl pagerBottomPrevContainer;
        protected HtmlGenericControl pagerBottomNextContainer;
        protected HtmlAnchor pagerBottomPrevLink;
        protected HtmlAnchor pagerBottomNextLink;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            postsRepeater.ItemDataBound += PostsRepeaterItemDataBound;
        }

        protected void PostsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var post = (NewsItemDto)e.Item.DataItem;

            var titleLink = (HtmlAnchor)e.Item.FindControl("postTitleField");
            titleLink.HRef = post.DisplayUrl;
            titleLink.InnerText = post.Title;

            //if((int)post["CommentsCount"] > 0)
            //{
            //    titleLink.InnerText += " (" + post["CommentsCount"] + ")";
            //}

            var authorLink = (HtmlAnchor)e.Item.FindControl("authorField");
            authorLink.InnerText = post.OwnerProfileName;
            authorLink.HRef = "/profile.aspx?ID=" + post.OwnerProfileId;

            var blogNameLink = (HtmlAnchor)e.Item.FindControl("blogNameField");
            //if (post.InfoSourceName == "ENETA Portaal") //dirty hack to hide source name
            if(post.OwnerProfileName == post.InfoSourceName)
                blogNameLink.Visible = false;
            blogNameLink.InnerText = post.InfoSourceName;
            blogNameLink.HRef = post.InfoSourceUrl;

            var postDateField = (HtmlContainerControl)e.Item.FindControl("postDateField");
            postDateField.InnerText = post.PublishDate.Date.ToShortDateString();

            var summaryField = (Label)e.Item.FindControl("summaryField");
            var body = RegExHelper.RemoveHtmlTags(post.Body);
            if (body.Length > 255)
                body = body.Substring(0, 255) + " [...]";
            summaryField.Text = body;

            var postLinkField = (HtmlAnchor)e.Item.FindControl("postLinkField");
            postLinkField.HRef = post.DisplayUrl;

            var commentsCountLink = (HtmlAnchor)e.Item.FindControl("commentsCountLink");
            if (post.Comments.Count > 0)
            {
                commentsCountLink.HRef = titleLink.HRef + "#comments";
                commentsCountLink.InnerHtml = "<span>(" + post.Comments.Count + ")</span>";
            }
            else
                commentsCountLink.Visible = false;

            var profileLink = (HtmlAnchor)e.Item.FindControl("profileLink");
            profileLink.HRef = authorLink.HRef;

            var profileRepository = new UserProfileRepository(SPContext.Current.Web);
            var profile = profileRepository.GetUserProfileById(post.OwnerProfileId);

            var profileImage = (HtmlImage)e.Item.FindControl("profileImage");
            profileImage.Src = profile.UserImage32x32Url; // "/_layouts/enetahandlers/userimagehandler.ashx?size=32&id=" + post.OwnerProfileId;

            var keywordsRepeater = (Repeater)e.Item.FindControl("keywordsRepeater");
            keywordsRepeater.ItemDataBound += KeywordsRepeaterItemDataBound;
            keywordsRepeater.DataSource = post.Keywords;
            keywordsRepeater.DataBind();

        }

        static void KeywordsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var keywordTitle = (HtmlGenericControl)e.Item.FindControl("tagLink");
            var keyword = (KeywordDto)e.Item.DataItem;
            keywordTitle.InnerText = keyword.Title;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                if (!string.IsNullOrEmpty(Request.QueryString["rss"]))
                {
                    Response.Clear();
                    Response.ContentType = "application/rss+xml";

                    var repository = new NewsItemRepository(SPContext.Current.Web);
                    Response.Write(repository.GetNewsItemsRss());

                    Response.End();
                    return;
                }
                if (!string.IsNullOrEmpty(Request.QueryString["commentsrss"]))
                {
                    Response.Clear();
                    Response.ContentType = "application/rss+xml";

                    var repository = new NewsItemRepository(SPContext.Current.Web);
                    var rss = repository.GetCommentsRss();
                    Response.Write(rss);

                    Response.End();
                    return;
                }

                var rows = GetNews();                
                postsRepeater.DataSource = rows;
                postsRepeater.DataBind();

                var master = Page.Master;
                if (master != null)
                {
                    //var link = (HtmlGenericControl)master.FindControl("rssMetaUrl");
                    var link = (HtmlLink)master.FindControl("rssMetaUrl");
                    if (link != null)
                    {
                        link.Attributes["title"] = "Eneta portaal: " + Resources.NewsAndBlogs.News;
                        link.Attributes["href"] = "http://rss.eneta.ee/eneta-uudised";
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogWarning("OnLoad: Exception occured", GetType().ToString());
                Logger.LogException(ex);
            }
        }

        private IList<NewsItemDto> GetNews()
        {
            var rep = new NewsItemRepository(SPContext.Current.Web);

            int page;
            var pageSize = 10;
            int.TryParse(Request.QueryString["page"], out page);
            if (page < 1)
                page = 1;

            var result = rep.GetApprovedNews(page, pageSize);

            if (Math.Max(1, page - 1) == 1)
                pagerPrevLink.HRef = "/uudised/Lehed/default.aspx";
            else
                pagerPrevLink.HRef = "/uudised/Lehed/default.aspx?page=" + Math.Max(1, page - 1);
            pagerBottomPrevLink.HRef = pagerPrevLink.HRef;

            if (Math.Min(result.PageCount, page + 1) == 1)
                pagerNextLink.HRef = "/uudised/Lehed/default.aspx";
            else
                pagerNextLink.HRef = "/uudised/Lehed/default.aspx?page=" + Math.Min(result.PageCount, page + 1);
            pagerBottomNextLink.HRef = pagerNextLink.HRef;

            if (page <= 1)
                pagerPrevContainer.Visible = false;
            if (page >= result.PageCount)
                pagerNextContainer.Visible = false;

            pagerBottomPrevContainer.Visible = pagerPrevContainer.Visible;
            pagerBottomNextContainer.Visible = pagerNextContainer.Visible;

            return result.Results;
        }        
    }
}
